﻿'Imports System.IO
'Imports System.Runtime
'Imports System.Text.Json

'Public Class TaskStore
'    Private Shared ReadOnly dataDir As String = TaskInfo.todoDataPath

'    Private Shared ReadOnly dataFile As String = Path.Combine(dataDir, "tasks.json")

'    Private Shared _tasks As List(Of TaskItem)

'    '——— 对外事件：任务集合变化时触发（增删改/载入/保存后均可触发一次） ———
'    Public Shared Event TasksChanged()

'    Shared Sub New()
'        LoadTasksFromDisk()
'    End Sub

'    Public Shared Property Tasks As List(Of TaskItem)
'        Get
'            Return _tasks
'        End Get
'        Set(value As List(Of TaskItem))
'            _tasks = value
'            SaveTasksToDisk()
'        End Set
'    End Property

'    '——— 统一的操作接口：确保任何改动都会保存并广播 ———
'    Public Shared Sub Add(task As TaskItem)
'        _tasks.Add(task)
'        SaveAndNotify()
'    End Sub

'    Public Shared Sub Update(task As TaskItem)
'        ' 找到已存在的任务并更新
'        Dim existingTask = _tasks.FirstOrDefault(Function(t) t.TaskDate = task.TaskDate AndAlso t.DueAt = task.DueAt)
'        If existingTask IsNot Nothing Then
'            existingTask.Description = task.Description
'            existingTask.IsCompleted = task.IsCompleted
'            existingTask.DueAt = task.DueAt
'            existingTask.HasNotified = task.HasNotified
'        End If

'        ' 任务是引用类型，属性修改后直接 SaveAndNotify 即可
'        SaveAndNotify()
'    End Sub

'    Public Shared Sub Remove(task As TaskItem)
'        _tasks.Remove(task)
'        SaveAndNotify()
'    End Sub

'    Public Shared Function GetTasksOf(d As Date) As List(Of TaskItem)
'        Return _tasks.Where(Function(t) t.TaskDate.Date = d.Date).ToList()
'    End Function


'    Public Shared Sub LoadTasksFromDisk()
'        Try
'            If File.Exists(dataFile) Then
'                Dim json = File.ReadAllText(dataFile)

'                ' 尝试反序列化为 List(Of TaskItem)
'                _tasks = JsonSerializer.Deserialize(Of List(Of TaskItem))(json, New JsonSerializerOptions With {.PropertyNameCaseInsensitive = True})

'                ' 如果反序列化失败，则初始化为空列表
'                If _tasks Is Nothing Then
'                    _tasks = New List(Of TaskItem)()
'                End If
'            Else
'                _tasks = New List(Of TaskItem)()
'            End If
'            RaiseEvent TasksChanged()
'        Catch ex As Exception
'            MessageBox.Show("读取任务数据失败：" & ex.Message)
'        End Try
'    End Sub

'    Private Shared Sub SaveAndNotify()
'        Try
'            If Not Directory.Exists(dataDir) Then Directory.CreateDirectory(dataDir)
'            Dim json = JsonSerializer.Serialize(_tasks, New JsonSerializerOptions With {.WriteIndented = True})
'            File.WriteAllText(dataFile, json)
'        Catch ex As Exception
'            MessageBox.Show("保存任务数据失败：" & ex.Message.ToString)
'        End Try
'        RaiseEvent TasksChanged()
'    End Sub

'    Public Shared Sub SaveTasksToDisk()
'        Try
'            If Not Directory.Exists(dataDir) Then Directory.CreateDirectory(dataDir)
'            Dim json = JsonSerializer.Serialize(_tasks, New JsonSerializerOptions With {.WriteIndented = True})
'            File.WriteAllText(dataFile, json)
'        Catch ex As Exception
'            MessageBox.Show("保存任务数据失败：" & ex.Message)
'        End Try
'    End Sub

'End Class


Imports System.IO
Imports System.Text.Json

Public Class TaskStore
    Private Shared ReadOnly dataDir As String = TaskInfo.todoDataPath
    Private Shared ReadOnly dataFile As String = Path.Combine(dataDir, "tasks.json")

    Private Shared _tasks As List(Of TaskItem)

    ' 对外事件：任务集合变化（增删改/载入/保存后均可触发）
    Public Shared Event TasksChanged()

    Shared Sub New()
        LoadTasksFromDisk()
    End Sub

    Public Shared Property Tasks As List(Of TaskItem)
        Get
            If _tasks Is Nothing Then _tasks = New List(Of TaskItem)()
            Return _tasks
        End Get
        Set(value As List(Of TaskItem))
            _tasks = If(value, New List(Of TaskItem)())
            SaveTasksToDisk()
            RaiseEvent TasksChanged()
        End Set
    End Property

    ' 统一操作接口（Id 驱动）

    Public Shared Sub Add(task As TaskItem)
        If task Is Nothing Then Return
        If _tasks Is Nothing Then _tasks = New List(Of TaskItem)()

        ' 确保有唯一 Id（兼容外部构造未赋值的情况）
        If String.IsNullOrWhiteSpace(task.Id) Then
            task.Id = Guid.NewGuid().ToString("N")
        End If

        _tasks.Add(task)
        SaveAndNotify()
    End Sub

    Public Shared Sub Update(task As TaskItem)
        If task Is Nothing Then Return
        If _tasks Is Nothing Then _tasks = New List(Of TaskItem)()

        ' 没有 Id 则补一个，视为新增
        If String.IsNullOrWhiteSpace(task.Id) Then
            task.Id = Guid.NewGuid().ToString("N")
            _tasks.Add(task)
            SaveAndNotify()
            Return
        End If

        ' 以 Id 精确定位
        Dim idx = _tasks.FindIndex(Function(x) x.Id = task.Id)
        If idx >= 0 Then
            ' 如果是同一实例，属性已被外部修改，保存并广播即可
            If Object.ReferenceEquals(_tasks(idx), task) Then
                SaveAndNotify()
            Else
                ' 使用外部传入对象替换原对象（或改为字段拷贝也可）
                _tasks(idx) = task
                SaveAndNotify()
            End If
        Else
            ' 未找到则视为新增（防御性）
            _tasks.Add(task)
            SaveAndNotify()
        End If
    End Sub

    Public Shared Sub Remove(task As TaskItem)
        If task Is Nothing Then Return
        RemoveById(task.Id)
    End Sub

    Public Shared Sub RemoveById(id As String)
        If String.IsNullOrWhiteSpace(id) Then Return
        If _tasks Is Nothing Then _tasks = New List(Of TaskItem)()

        Dim removed = _tasks.RemoveAll(Function(x) x.Id = id)
        If removed > 0 Then
            SaveAndNotify()
        End If
    End Sub

    Public Shared Function FindById(id As String) As TaskItem
        If String.IsNullOrWhiteSpace(id) Then Return Nothing
        If _tasks Is Nothing Then Return Nothing
        Return _tasks.FirstOrDefault(Function(x) x.Id = id)
    End Function

    Public Shared Function GetTasksOf(d As Date) As List(Of TaskItem)
        If _tasks Is Nothing Then _tasks = New List(Of TaskItem)()
        Return _tasks.Where(Function(t) t.TaskDate.Date = d.Date).ToList()
    End Function

    Public Shared Sub LoadTasksFromDisk()
        Try
            If File.Exists(dataFile) Then
                Dim json = File.ReadAllText(dataFile)

                _tasks = JsonSerializer.Deserialize(Of List(Of TaskItem))(
                    json,
                    New JsonSerializerOptions With {.PropertyNameCaseInsensitive = True}
                )

                If _tasks Is Nothing Then _tasks = New List(Of TaskItem)()
            Else
                _tasks = New List(Of TaskItem)()
            End If

            ' 迁移：为历史数据补 Id
            Dim changed As Boolean = False
            For Each t In _tasks
                If t IsNot Nothing AndAlso String.IsNullOrWhiteSpace(t.Id) Then
                    t.Id = Guid.NewGuid().ToString("N")
                    changed = True
                End If
            Next
            If changed Then
                ' 保存一次，确保磁盘上的数据也带 Id，后续更稳定
                SaveTasksToDisk()
            End If

            RaiseEvent TasksChanged()
        Catch ex As Exception
            MessageBox.Show("读取任务数据失败：" & ex.Message)
            If _tasks Is Nothing Then _tasks = New List(Of TaskItem)()
        End Try
    End Sub

    ' 当你只是需要“保存+广播”而不想更新某一条（比如 Timer 批量改了多条的 HasNotified）
    Public Shared Sub NotifyChanged()
        SaveAndNotify()
    End Sub

    Private Shared Sub SaveAndNotify()
        Try
            If _tasks Is Nothing Then _tasks = New List(Of TaskItem)()
            If Not Directory.Exists(dataDir) Then Directory.CreateDirectory(dataDir)
            Dim json = JsonSerializer.Serialize(_tasks, New JsonSerializerOptions With {.WriteIndented = True})
            File.WriteAllText(dataFile, json)
        Catch ex As Exception
            MessageBox.Show("保存任务数据失败：" & ex.Message)
        End Try
        RaiseEvent TasksChanged()
    End Sub

    Public Shared Sub SaveTasksToDisk()
        Try
            If _tasks Is Nothing Then _tasks = New List(Of TaskItem)()
            If Not Directory.Exists(dataDir) Then Directory.CreateDirectory(dataDir)
            Dim json = JsonSerializer.Serialize(_tasks, New JsonSerializerOptions With {.WriteIndented = True})
            File.WriteAllText(dataFile, json)
        Catch ex As Exception
            MessageBox.Show("保存任务数据失败：" & ex.Message)
        End Try
    End Sub
End Class

